package com.stylefeng.guns.modular.huamao.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stylefeng.guns.core.util.MD5Util;
import com.stylefeng.guns.modular.huamao.model.SktExchangeUser;
import com.stylefeng.guns.modular.huamao.model.Users;
import com.stylefeng.guns.modular.huamao.result.Result;
import com.stylefeng.guns.modular.huamao.service.IAccountService;
import com.stylefeng.guns.modular.huamao.service.ISktExchangeUserService;
import com.stylefeng.guns.modular.huamao.service.ISktHuamaobtLogService;
import com.stylefeng.guns.modular.huamao.service.IUsersService;
import com.stylefeng.guns.modular.huamao.util.HttpUtil;
import com.stylefeng.guns.modular.huamao.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
@CrossOrigin
@RequestMapping("/app")
public class AppExchangeUserController {

    @Autowired
    ISktExchangeUserService sktExchangeUserService;

    @Autowired
    ISktHuamaobtLogService sktHuamaobtLogService;

    @Autowired
    IUsersService usersService;

    @Autowired
    IAccountService accountService;

    /**
     * 注册交易所账号
     * @param userId
     * @return
     */
    @RequestMapping(value = "/exchangeUser/register")
    @ResponseBody
    public Result register(Integer userId) {

        /**
         * 判断用户是否已经注册
         */
        SktExchangeUser sktExchangeUser1 = new SktExchangeUser();
        sktExchangeUser1.setUserId(userId);
        SktExchangeUser rsktExchangeUser = new SktExchangeUser();
        EntityWrapper<SktExchangeUser> entityWrapper = new EntityWrapper<SktExchangeUser>(sktExchangeUser1);
        rsktExchangeUser =sktExchangeUserService.selectOne(entityWrapper);
        if (rsktExchangeUser !=  null){
            return Result.EEROR("用户已经注册，无需重复注册");
        }



        Users users = new Users();
        users = usersService.selectById(userId);


        String url = "https://api1.digsg.com/user/register";
        String companyID = "1";
        //String userMobile= "15308488113";
        String userMobile= users.getUserPhone();
        String secretKey = "iL34.#dnZ2ubJJFt";

        String key = userMobile+companyID+secretKey;

        String md5Info = MD5Util.encrypt(key);
        //String md5Info = "8ba6fb79659105c37a4b27b5af63d513";

        Map<String,Object> map = new HashMap<String, Object>();
        map.put("companyID",companyID);
        map.put("userMobile",userMobile);
        map.put("md5Info",md5Info);

        /**
         *调用注册接口
         */
        String json =  HttpUtil.doPost(url,map);
        JSONObject jsonObject = JSONObject.parseObject(json);
        if(jsonObject.getBoolean("isSuc")){

            JSONObject datas = jsonObject.getJSONObject("datas");

            SktExchangeUser sktExchangeUser = new SktExchangeUser();
            sktExchangeUser.setUserId(users.getUserId());
            sktExchangeUser.setUserPhone(users.getUserPhone());
            sktExchangeUser.setLoginName(users.getLoginName());
            sktExchangeUser.setExchangeUserId(datas.getInteger("userID"));
            sktExchangeUser.setCreateTime(new Date());
            try{
                sktExchangeUserService.insert(sktExchangeUser);
                return Result.OK("注册成功");
            }catch (Exception e){
                return  Result.EEROR("注册失败");
            }
        }else {
            return Result.EEROR(jsonObject.getString("des"));
        }

    }

    /**
     * 用户充值（华宝转猫币）
     * @param userId
     * @param huamao
     * @return
     */
    @RequestMapping(value = "/exchangeUser/recharge")
    @ResponseBody
    public Object recharge(Integer userId,BigDecimal huamao){

        BigDecimal cnyPrice = new BigDecimal(sktHuamaobtLogService.ticker().toString());

        /**
         * 此处的huamao是初始华宝的值初始单位是分，需要转换成元，
         * 并且要计算税率，此处暂时不做处理,直接除利率得出猫币。（猫币换算成元除以利率）
         */
        BigDecimal amount = huamao.divide(cnyPrice,2, RoundingMode.HALF_UP);
        /**
         * huamao初始化的华宝的数量（扣除华宝，增加记录的使用）
         * amount转换成猫币的数量
          */
        return sktHuamaobtLogService.recharge(userId,huamao,amount,StringUtils.getOrderIdByTime("5"));
    }

}
